package ua.dou.utils;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.google.code.rome.android.repackaged.com.sun.syndication.feed.atom.Entry;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: funbox
 * Date: 3/31/13
 * Time: 5:36 AM
 * To change this template use File | Settings | File Templates.
 */
public class DBOpenHelper extends SQLiteOpenHelper {

    private static final int DATABASE_VERSION = 2;
    private static final String DATABASE_NAME = "DOUAPP";
    private static final String TABLE_NAME = "ENTRIES";
    private static final String TABLE_CREATE = "CREATE TABLE " + TABLE_NAME + " (" +
            "id INTEGER PRIMARY KEY AUTOINCREMENT, ENTRY BLOB);";

    public DBOpenHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(TABLE_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i2) {

    }

    private void addEntry(Entry entry) {
        SQLiteDatabase db = this.getWritableDatabase();

        byte[] b = Utils.serializeEntry(entry);

        ContentValues values = new ContentValues();
        values.put("ENTRY", b); // Contact Name

        db.insert(TABLE_NAME, null, values);
        db.close();
    }

    public void addEntries(List<Entry> entries) {
        for(Entry entry: entries){
            addEntry(entry);
        }
    }

    public List<Entry> getAllEntries() {

        List<Entry> entries = new ArrayList<Entry>();

        String selectQuery = "SELECT  * FROM " + TABLE_NAME;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
        Entry entry;

        if (cursor.moveToFirst()) {
            do {
                entry = Utils.deserializeEntry(cursor.getBlob(0));
                entries.add(entry);
            } while (cursor.moveToNext());
        }

        return entries;
    }

}